/**
 * @author Daniel Robenek
 * @license MIT
 */

/**
 * 	$(document).ready(function() {
 *		$.dependentselectbox.initialize();
 *	});
 *
 *	Add to jquery.nette.js at the end of $.nette.success:
 *	$.dependentselectbox.hideSubmits();
 *	or use livequery
 */
jQuery.extend({
	dependentselectbox: {
		controlClass: 'dependentControl',

		buttonSuffix: '_submit',

		hideSubmits: function() {
			// Here hide all you want. Default is to hide <tr> of button
			$('.'+$.dependentselectbox.controlClass+$.dependentselectbox.buttonSuffix).parent().parent().hide();
		},

		initialize: function() {
			$.dependentselectbox.hideSubmits();
			$('.'+$.dependentselectbox.controlClass).live('change', function() {
				// Nette form validation
				button = document.getElementById(($(this).attr('id'))+$.dependentselectbox.buttonSuffix);
				button.form["nette-submittedBy"] = button;
				// ----
				$('#'+($(this).attr('id'))+$.dependentselectbox.buttonSuffix).ajaxSubmit($.dependentselectbox.jsonResponse);
			});
		},

		updateSelectBox: function(id, selectedKey, items) {
			$("#" + id + " option").remove();
			var select = $("#" + id);
			for(var i in items) {
				var item = $("<option></option>").attr("value", i).html(items[i]);
				if(i == selectedKey)
					item.attr("selected", "selected");
				if(i == "")
				  select.prepend(item);
				else
				  select.append(item);
			}
		},

		jsonResponse: function(payload) {
			if(!(payload["type"] && payload["type"] == "JsonDependentSelectBoxResponse")) {
				$.nette.success(payload);
				return;
			}
			var items = payload["items"];
			for(var i in items) {
				$.dependentselectbox.updateSelectBox(i, items[i]["selected"], items[i]["items"]);
			}
		}
	}
});

$(document).ready(function() {
	$.dependentselectbox.initialize();

});

$.fn.ajaxSubmit = function(process) {
	/* Change a form's submission type to ajax */
	
		var params = {};
		$(this)
		.find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea")
		.filter(":enabled")
		.each(function() {
			params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
		});
		var action = $(this).parents('form')[0].getAttribute('action');
		$("body").addClass("curWait");
		$.post(action, params, function(payload){
			console.log(payload);
			process(payload);
		});
		return false;

}

function projectChanged(el, url){
	url = url.toString().replace('__project__', $(el).val());
	$.get(url, function(payload){
		for( i in payload.members){
			//members.empty();
			//members.append('option').val(payload.members[i]).text(payload.members[i]);
		}
	});
}